<?php
/**
  * wechat php test
  */

//define your token
define("TOKEN", "tanghn");
/*返回最大记录数*/
define("MAXRECORDS", 3);
define("MSGTYPE", "news");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->responseMsg();

/*按微信格式组装消息，*/
function AssembleMenuMsg($lines_array, $from, $to){

	$counter = count($lines_array);
	$counter = ($counter>MAXRECORDS) ? MAXRECORDS : $counter;
	$time = time();
	
	$textTpl = sprintf("<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[news]]></MsgType>
							<ArticleCount>%s</ArticleCount>
							<Articles>
							", $to, $from, $time, $counter);
							
	for($i=0; $i < $counter; $i++){
		$row = $lines_array[$i][0];
		$id = $row['id'];
		$data = sprintf("$i: %s %f元",$row['name'], $row['price']);
		$textTpl = $textTpl.sprintf("<item>
							<Title><![CDATA[%s]]></Title>
							<Description><![CDATA[descpUnused]]></Description>
							<PicUrl><![CDATA[%s]]></PicUrl>
							<Url><![CDATA[%s]]></Url>
							</item>
							", $data,"http://tanghn.xicp.net/8.gif", "http://tanghn.xicp.net/row.php?id=$id");
	}

	$textTpl = $textTpl."</Articles>
							</xml>";
	return $textTpl;
}

/*array(id,name,price,count)*/
function AssembleShoppingboxMsg($lines_buy, $from, $to){

	$counter = count($lines_buy);
	$time = time();
	
	if($counter>0){
		$textTpl = sprintf("<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[news]]></MsgType>
							<ArticleCount>%s</ArticleCount>
							<Articles>
							", $to, $from, $time, $counter);
		
		$textTpl = 	$textTpl.sprintf("<item>
								<Title><![CDATA[购物车]]></Title>
								<Description><![CDATA[descpUnused]]></Description>
								<PicUrl><![CDATA[%s]]></PicUrl>
								<Url><![CDATA[%s]]></Url>
								</item>
								", "http://tanghn.xicp.net/null.gif", "www.baidu.com");
								
		for($i=0; $i < $counter; $i++){
			$name = $lines_buy[$i][1]; /*careful!!*/
			$price = $lines_buy[$i][2];
			$counter = $lines_buy[$i][3];
			
			$data = sprintf("%s,%d个: 小计%f元",$name, $counter，($counter * $price));
			$textTpl = $textTpl.sprintf("<item>
								<Title><![CDATA[%s]]></Title>
								<Description><![CDATA[descpUnused]]></Description>
								<PicUrl><![CDATA[%s]]></PicUrl>
								<Url><![CDATA[%s]]></Url>
								</item>
								", $data,"http://tanghn.xicp.net/8.gif", "www.baidu.com");
		}

		$textTpl = $textTpl."</Articles>
								</xml>";
	}else{
	$textTpl = $textTpl.sprintf("<xml>
								 <ToUserName><![CDATA[%s]]></ToUserName>
								 <FromUserName><![CDATA[%s]]></FromUserName>
								 <CreateTime>%s</CreateTime>
								 <MsgType><![CDATA[text]]></MsgType>
								 <Content><![CDATA[%s]]></Content>
								 </xml>
								", $to, $from, $time, "没有购买商品，谢谢惠顾！");
		
	}
	return $textTpl;
}

/*未命中时打印默认菜单，考虑随机打印？？默认查询较慢需要优化？？*/
/*返回结果参考SearchMenu*/
function DefaultMenu(){
	$con = mysql_connect("tanghn.xicp.net","root","redhat");
	if (!$con)
	{
		die('Could not connect: ' . mysql_error());
	}

	mysql_select_db("kfcmenu", $con);
	mysql_query("set names utf8");

	$temp = "SELECT * FROM kfcmenu";
	$db_result = mysql_query($temp);

	unset($lines_array);
	$lines_array = array();
	while($row = mysql_fetch_array($db_result))
	{
		$match_times = 0;
		$temp = array($row, $match_times);
		array_push($lines_array, $temp);
	}

	mysql_close($con);
	
	return $lines_array;
}

/*命中关键字时的结果，结果类型是array(array(id,name,price,keyword,description,retrieval_times,hit_times),match_times)*/
function SearchMenu($k){
	$con = mysql_connect("127.0.0.1","root","redhat");
	if (!$con)
	{
		die('Could not connect: ' . mysql_error());
	}

	$text = $k;
	$text = iconv("UTF-8", "GBK//IGNORE", $text);
	$text = urlencode($text);
	$result = file_get_contents("http://192.168.1.22:1985/?w=".$text);
	$result = iconv("GBK", "UTF-8//IGNORE", $result);

	$fenci = explode(" ", $result);

	mysql_select_db("kfcmenu", $con);
	mysql_query("set names utf8");

	$temp = "SELECT * FROM kfcmenu";
	$db_result = mysql_query($temp);

	unset($lines_array);
	$lines_array = array();
	while($row = mysql_fetch_array($db_result))
	{
		$match_times = 0;
		/*unset($lines_array); 清空变量*/

		foreach ($fenci as $current_keyword){
				if(eregi($current_keyword, $row['keyword']))  /*strstr不能匹配，不明原因。使用正则表达式*/
				/*if(false != stristr($current_keyword, $row['keyword']))*/
				{
					$match_times++;
				}
		}
		if($match_times>0){
			$temp = array($row, $match_times);
			array_push($lines_array, $temp);
		}else{
			continue;
		}
	}

	usort($lines_array, 'compare');
	
	mysql_close($con);
	
	return $lines_array;
}
/*逆序*/
function compare($x, $y){
	if($x[1] == $y[1]){
		return 0;
	}else if($x[1] < $y[1]){
		return 1;
	}else{
		return -1;
	}
}

class wechatCallbackapiTest
{
	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }

    public function responseMsg()
    {
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		@ $fp = fopen("debug.txt", 'ab');

      	//extract post data
		if (!empty($postStr)){
			session_start();
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$fromUsername = $postObj->FromUserName;
			$toUsername = $postObj->ToUserName;
			$content = trim($postObj->Content);
			
			if(empty( $content )){
				echo "111111111111...";
				exit;
			}
			
			if(eregi('^bye$', $content)){
				/*mark  need print*/
				fwrite($fp, "byebyte.\r\n");
				session_destroy();
				fclose($fp);
				exit;
			}
			
			$_SESSION['status']++;
			$debug = sprintf("%d",$_SESSION['status']);
			fwrite($fp, $debug."\r\n");
			fclose($fp);
			exit;
/********************************************init*********************************************/
			if(!isset($_SESSION['status'])){ 
				fwrite($fp, "STATUS empty\r\n");
				$debug = print_r($_SESSION['lastmenu']);
				fwrite($fp, $debug."\r\n");
				$debug = print_r($_SESSION['shoppingbox']);
				fwrite($fp, $debug."\r\n");
				
				$menu = SearchMenu($content);
				if(count($menu)<=0){ /*not hit*/
					$menu = DefaultMenu();
				}

				$post_msg = AssembleMenuMsg($menu, $toUsername, $fromUsername);
				echo $post_msg;	
				$_SESSION['status'] = 1;
				$_SESSION['lastmenu'] = $menu;
				$debug = print_r($menu);
				fwrite($fp, $debug."\r\n");
				
/***************************************check menu********************************************/
			}else if($status==1){
				fwrite($fp, "STATUS value is 1.\r\n");
				$debug = print_r($_SESSION['lastmenu']);
				fwrite($fp, $debug."\r\n");
				$debug = print_r($_SESSION['shoppingbox']);
				fwrite($fp, $debug."\r\n");
				
				$content =preg_replace("/\s/","",$content); /*del white character*/
				
				if(eregi('^ok$', $content)){/*hit 'ok', go to checkout*/
					AssembleShoppingboxMsg($_SESSION['lastmenu'], $toUsername, $fromUsername);
					session_destroy();
					exit;
				}
				if(eregi('^[0-9]*+$', $content)){/*buy!*/
					$number_str = explode('!', $content);
					$num = intval($number_str[0], 10);
					
					$lastmenu = $_SESSION['lastmenu'];
					
					if(isset($_SESSION['shoppingbox']['name'])){
						$_SESSION['shoppingbox']['name']++;
					}else{
						$item = array($lastmenu[$num]['id'], $lastmenu[$num]['name'], $lastmenu[$num]['price'], 1); /*mark 图片*/
						array_push ($_SESSION['shoppingbox'], $item);
					}
					AssembleShoppingboxMsg($_SESSION['shoppingbox'], $toUsername, $fromUsername);
				}else{/*打印上次菜单*/
					$menu = SearchMenu($content);
					if(count($menu)>0){  /*re-search*/
						$menu = DefaultMenu();
						$post_msg = AssembleMenuMsg($menu, $toUsername, $fromUsername);
						echo $post_msg;	
						$_SESSION['status'] = 1;
						$_SESSION['lastmenu'] = $menu;
					}else{ /*invalid input, just keep*/
						exit;
					}
				}
			}
        }else {
        	echo "222222";
        }
		fclose(fp);
		exit;
    }
		
	private function checkSignature()
	{
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];	
        		
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}

}


?>